package vn.edu.saigontech.ncms.web.ajaxtags;

import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sourceforge.ajaxtags.servlets.BaseAjaxServlet;
import net.sourceforge.ajaxtags.xml.AjaxXmlBuilder;

import org.hibernate.Session;
import org.hibernate.Transaction;

import vn.edu.saigontech.ncms.model.info.Offering;
import vn.edu.saigontech.ncms.model.info.OfferingMember;
import vn.edu.saigontech.ncms.service.OfferingService;
import vn.edu.saigontech.ncms.util.Checker;
import vn.edu.saigontech.ncms.util.HibernateUtil;

@SuppressWarnings("serial")
public class OfferingMemberServlet extends BaseAjaxServlet {

	@Override
	public String getXmlContent(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String offeringId = request.getParameter("offeringId");
		AjaxXmlBuilder xml = new AjaxXmlBuilder();
		Session session = null;
		Transaction trans = null;
		Set<OfferingMember> members = new HashSet<OfferingMember>();
		Map<Long, String> ret = new HashMap<Long, String>();
		try {
			session = HibernateUtil.getCurrentSession();
			trans = session.beginTransaction();
			Offering offering = OfferingService.INSTANCE.findById(Long.parseLong(offeringId));
			if (Checker.isNotNull(offering)) {
				members = offering.getMembers();
			}
			for (OfferingMember member : members) {
				ret.put(member.getId(), member.getReceipt().getStudent().getFullName());
			}
			trans.commit();
		} catch (Exception ex) {
			if (trans != null) {
				trans.rollback();
			}
		} finally {
			if (session != null) {
				session.close();
			}
		}
		for (Entry<Long, String> entry : ret.entrySet()) {
			xml.addItem(entry.getValue(), true, entry.getKey().toString());
		}
		return xml.toString();
	}
}